package com.moyuxi.sound_of_the_forest.ui.compose

import android.graphics.BitmapFactory
import android.media.MediaMetadataRetriever
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.moyuxi.sound_of_the_forest.R


@Composable
fun MusicImageCompose(
    filePath: String,
    modifier: Modifier = Modifier
        .size(100.dp)
        .padding(5.dp),
    contentScale: ContentScale = ContentScale.FillWidth
) {
    val mmr = MediaMetadataRetriever()
    val bytes = if (filePath.isNotEmpty()) {
        mmr.setDataSource(filePath)
        mmr.embeddedPicture
    } else null
    if (bytes != null) {
        val albumPicture = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
//        val width: Int = albumPicture.width
//        val height: Int = albumPicture.height
//        val matrix = Matrix()
//        val sx = 120f / width
//        val sy = 120f / height
//        matrix.postScale(sx, sy)
//        albumPicture = Bitmap.createBitmap(albumPicture, 0, 0, width, height, matrix, false);
        Image(
            bitmap = albumPicture.asImageBitmap(),
            contentDescription = "歌手图像",
            modifier,
            contentScale = contentScale
        )
    } else {
        Image(
            painter = painterResource(id = R.drawable.icon_music),
            contentDescription = "歌手图像",
            modifier,
            contentScale = contentScale

        )
    }
    try {
        mmr.release()
    } catch (e: Exception) {
        Log.i("TAG", "MusicImageCompose: ${e.message}")
    }
}